package com.onemile.utils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class UtiXmlDocument
{
	private Document _doc;
	private Element _root;
	
	public UtiXmlDocument(String xml) throws IOException
	{
		loadXml(xml.getBytes());
	}
	
	public UtiXmlDocument(byte[] bytes) throws IOException
	{
		loadXml(bytes);
	}
	
	private void loadXml(byte[] bytes) throws IOException
	{
		try
		{
			InputStream in = new ByteArrayInputStream(bytes);
			DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
			fac.setCoalescing(true);
			DocumentBuilder builder = fac.newDocumentBuilder();
			_doc = builder.parse(in);
			_root = _doc.getDocumentElement();
		}
		catch (Exception e)
		{
			throw new IOException(e.toString());
		}
	}
	
	public Element getElementRoot()
	{
		return _root;
	}
	
	public Element getElement(String tagName)
	{
		NodeList nodes = _doc.getElementsByTagName(tagName);
		if (nodes != null && nodes.getLength() > 0)
		{
			return (Element) nodes.item(0);
		}
		else
		{
			return null;
		}
	}
}
